# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA

# Based on Message Duplexer perl plugin on http://www.gamerotor.com/node/270

use Purple;
use Encode;

my $norecurse = 0;
my $pretobuddyDisplayName = 0;
my $bkpaccount = 0;

%PLUGIN_INFO = (
	perl_api_version => 2,
	name => "Forward2Mobile",
	version => "0.2",
	summary => "Forward IM messages to your favourite mobile IM client/account",
	description => "Forward IM messages to your favourite mobile IM client/account and 
	\send your IM messages from your favourite mobile IM client/account to specified user syntax is to:message",
	author => "Caglar Oral",
	url => "",

	load => "plugin_load",
	unload => "plugin_unload",
	prefs_info => "prefs_info_cb"
);

sub plugin_init {
	return %PLUGIN_INFO;
}

sub plugin_load {
	$plugin = shift;

	Purple::Debug::info("f2m", "plugin_load() - begin\n");

	# Preferences
	Purple::Prefs::add_none("/plugins/core/f2m");
	Purple::Prefs::add_string("/plugins/core/f2m/bkpcontact", "???");

	# A pointer to the handle to which the signal belongs
	$convs_handle = Purple::Conversations::get_handle();

	# Connect the perl sub 'sending_im_msg_cb' to the event 'sending-im-msg'
	# Purple::Signal::connect($convs_handle, "sending-im-msg", $plugin,
	# \&sending_im_msg_cb, "xxx");

	# Connect the perl sub 'receiving_im_msg_cb' to the event 'receiving-im-msg'
	Purple::Signal::connect($convs_handle, "receiving-im-msg", $plugin, \&receiving_im_msg_cb, "yyy");
	
	# File receive and forward support
	#Purple::Signal::connect(Purple::Xfers::get_handle(), "file-recv-request", $plugin, \&file_recv_request_cb);

	Purple::Debug::info("f2m", "plugin_load() - f2m plugin loaded\n");
}

sub plugin_unload {
	my $plugin = shift;
	Purple::Debug::info("f2m", "plugin_unload() - f2m plugin unloaded.\n");
}

sub file_recv_request_cb {
        my ($xfer,$data) = @_;
        # Code
}

sub dup_msg {	
	if ($norecurse == 0) {
		$norecurse++;
		
		my ($account, $theSender, $msg, $buddyDisplayName) = @_;
		my $bkpcontact = Purple::Prefs::get_string("/plugins/core/f2m/bkpcontact");
		my $convOut;
		my $im;
		@accounts = Purple::Accounts::get_all();
		
		if ($theSender eq $bkpcontact) {
			# @ Commands
			# @list
			if ($msg =~ m/^@/) {
				if($msg eq "\@plist") {
					for ($i=0; $i<=$#accounts; $i++) {
						@buddy_array = Purple::Find::buddies($accounts[$i], undef);
						if (@buddy_array) {
							foreach $tobuddy (@buddy_array) {
								$buddystatus = Purple::Presence::get_active_status(Purple::BuddyList::Buddy::get_presence($tobuddy));
								if ($buddystatus) {
									$buddystatusid = Purple::Status::get_id($buddystatus);
									if (($buddystatusid ne "OFFLINE") && ($buddystatusid ne "offline")) {
										push(@onlinelist, Purple::BuddyList::Buddy::get_alias($tobuddy));
									}
								}
							}
						}					
					    $bkpaccount = $accounts[$i];
						$buddy = Purple::Find::buddy($accounts[$i], $bkpcontact);
						if($buddy) {
							$convOut = Purple::Conversation->new(1, $accounts[$i], $bkpcontact);
						}
					}
					if ($convOut) {
						$im = $convOut->get_im_data();
						@sortedonlinelist = sort {$a <=> $b || lc($a) cmp lc($b)} @onlinelist;
						@sortedonlinelist = join(", ",@sortedonlinelist);
						$im->send("@sortedonlinelist");
						undef @onlinelist;
						undef @sortedonlinelist;
						$convOut->destroy();
					}
				}
			
				if($msg eq "\@paway") {
					$saved_status = Purple::SavedStatus::get_current();
					$saved_status->set_type(5);
					$saved_status->activate();
				}
					
				if($msg eq "\@ponline") {
					$saved_status = Purple::SavedStatus::get_current();
					$saved_status->set_type(2);
					$saved_status->activate();
					$account->set_status("available", TRUE);
				}
					
				if($msg eq "\@pinvisible") {
					$saved_status = Purple::SavedStatus::get_current();
					$saved_status->set_type(4);
					$saved_status->activate();
					$account->set_status("invisible", TRUE);
				}
			} else {
				
				#Message received from me
				$msgsent = 0;
				$position = index($msg, ":");
				
				if ($position > 0) {
					$toMessage = substr($msg, $position + 1);
					$tobuddyDisplayName = substr($msg, 0, $position);
				} else {
					$toMessage = $msg;
					$tobuddyDisplayName = $pretobuddyDisplayName;
				}
SENDMSG:				
				for ($i=0; $i<=$#accounts; $i++) {
					@buddy_array = Purple::Find::buddies($accounts[$i], undef);
					if (@buddy_array) {
						foreach $tobuddy (@buddy_array) {						
							$u2string = $tobuddy->get_alias();
							$tobuddyName = $tobuddy->get_name();
							$tmptobuddyName = decode_utf8($u2string);
						
							if($tmptobuddyName eq $tobuddyDisplayName) {
								$pretobuddyDisplayName = $tobuddyDisplayName;
								$convTo = Purple::Conversation->new(1, $accounts[$i], $tobuddyName);
								if ($convTo) {
									$im = $convTo->get_im_data();
									$im->send($toMessage);
									$convTo->destroy();
									$msgsent = 1;
								}	
							}
						}			
					}			
				}
				
				if ($msgsent == 0){
					#Check the string after ':' for some text emotions
					$emotion = substr($msg, $position + 1, 1);
					if ($emotion =~ m/\W|[dbspoxe]/i) {
						$toMessage = $msg;
						$tobuddyDisplayName = $pretobuddyDisplayName;	
						goto SENDMSG;	
					} else {
						#Send "cannot find buddy name" message
						for ($i=0; $i<=$#accounts; $i++) {
							$buddy = Purple::Find::buddy($accounts[$i], $bkpcontact);
							if($buddy) {
								$convOut = Purple::Conversation->new(1, $accounts[$i], $bkpcontact);
							}
						}
									
						if ($convOut) {
							$im = $convOut->get_im_data();
							$im->send("Cannot find buddy ".$tobuddyDisplayName." in your contact list. Please double check buddy name in your message\n");
							$convOut->destroy();
						}
					}			
				}		 
			}
		} else {
		
		#Message received from my contacts
			for ($i=0; $i<=$#accounts; $i++) {
				$buddy = Purple::Find::buddy($accounts[$i], $bkpcontact);
				if($buddy) {
					$convOut = Purple::Conversation->new(1, $accounts[$i], $bkpcontact);
				}
			}
		
			if ($convOut) {
				$im = $convOut->get_im_data();
				($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
				$year = 1900 + $yearOffset;
				$theTime = "($hour:$minute) ";

				$im->send($theTime.$buddyDisplayName.": ".$msg);
				$convOut->destroy();
			}
		}
		$norecurse--;
	}
}

sub sending_im_msg_cb {
	my ($account, $who, $msg) = @_;
	$accountname = $account->get_username();

	dup_msg($account, $who, $msg, "outcoming");

}

sub receiving_im_msg_cb {
	my ($account, $who, $msg, $conv, $flags) = @_;
	$accountname = $account->get_username();

	@accounts = Purple::Accounts::get_all();
	for ($i=0; $i<=$#accounts; $i++) {
		$sender = Purple::Find::buddy($accounts[$i], $who);
		if($sender) {
			$ustring = $sender->get_alias();
			$theSender = $sender->get_name();
			$buddyDisplayName = decode_utf8($ustring);
		}	
	}

	dup_msg($account, $theSender, $msg, $buddyDisplayName);

}

sub prefs_info_cb {
	# Get all accounts to show in the drop-down menu
	@accounts = Purple::Accounts::get_all();

	$frame = Purple::PluginPref::Frame->new();
	if (0) {
		$acpref = Purple::PluginPref->new_with_name_and_label("/plugins/core/f2m/account", "Forward2Mobile: ");
		$acpref->set_type(1); # To indicate a drop-down choice
		@acnames = [];
		for ($i=0; $i<=$#accounts; $i++) {
			$acnames[$i] = $accounts[$i]->get_username();
		}

		for ($i=0; $i<=$#acnames; $i++) {
		$acpref->add_choice($acnames[$i], $acnames[$i]);
		}

		$acpref->add_choice("None", "None"); # The default choice
		$frame->add($acpref);
	}

	$bkpcontact = Purple::PluginPref->new_with_name_and_label("/plugins/core/f2m/bkpcontact", "Mobile account (fe. gtalk id): ");
	$bkpcontact->set_type(2);
	$bkpcontact->set_max_length(120);
	$frame->add($bkpcontact);

	return $frame;
}
